package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.LoginDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.user.ResponseLoginDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.user.ApUser;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;


@Service
public class ApUserServiceImpl extends ServiceImpl<UserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(LoginDto dto) {

        //1.正常登录（手机号+密码登录）
        //判断数据是否为空
        if (!StringUtils.isBlank(dto.getPhone()) && !StringUtils.isBlank(dto.getPassword())) {
            String phone = dto.getPhone();
            //正则匹配手机号正确格式
            boolean matches = phone.matches("^(13[0-9]|14[5-9]|15[0-35-9]|16[25-7]|17[0-8]|18[0-9]|19[0135689])[0-9]{8}$");
            if (!matches) {
                //匹配不通过
                return ResponseResult.errorResult(AppHttpCodeEnum.PHONE_NUMBER_ERROR);
            }
            //1.1查询用户
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser apUser = getOne(queryWrapper);
            //如果改手机号未查询到用户
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
            //1.2 比对密码
            String salt = apUser.getSalt();
            String pswd = dto.getPassword();
            //加盐后对比
            pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
            if (!pswd.equals(apUser.getPassword())) {
                //密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.3 返回数据  jwt
            String jwt = AppJwtUtil.getToken(apUser.getId().longValue());
            //脱敏
            apUser.setSalt("");
            apUser.setPassword("");
            return ResponseResult.okResult(new ResponseLoginDto(apUser, jwt));
        } else {
            //2.游客  同样返回token  id = 0
            HashMap<String, String> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}

